package com.appspot.didit.server;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.appspot.didit.client.workitem.Workitem;
import com.appspot.didit.client.workitem.WorkitemService;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class WorkitemServiceImpl extends RemoteServiceServlet implements WorkitemService {
	
	private static final Logger LOG = Logger.getLogger(WorkitemServiceImpl.class.getName());
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		resp.sendRedirect("/");
		return;
	}
	
	public void update(Workitem wi) {
	    PersistenceManager pm = PMF.get().getPersistenceManager();
	    try {
	    	Workitem oldWi = pm.getObjectById(Workitem.class, wi.getId());
	    	oldWi.update(wi);
	    } catch (Exception e) {
	    	LOG.logp(Level.FINE, "WorkitemServiceImpl", "save", e.toString());
	    } finally {
	      pm.close();
	    }
	}

	public Workitem save(Workitem wi) {
		Workitem wi1 = new Workitem();
		PersistenceManager pm = PMF.get().getPersistenceManager();
	    try {
	    	Date d = wi.getDate();
	    	if(d.getHours() > 21) {
	    		wi.setDate(new Date(d.getTime() + (24-d.getHours())*60*60*1000L));
	    	}
			pm.makePersistent(wi);
	    	wi1 = wi;
	    	System.out.println(wi);
	    } catch (Exception e) {
	    	LOG.logp(Level.FINE, "WorkitemServiceImpl", "save", e.toString());
	    } finally {
	      pm.close();
	    }
	    return wi1;
	}
	
	
	public ArrayList<Workitem> loadWorkitems(Long user_id) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		ArrayList<Workitem> workitems = new ArrayList<Workitem>(); 
		try {
			/*System.out.println("deleting all!");
	    	String sql0 = "SELECT FROM " + Workitem.class.getName();
			List<Workitem> results = (List<Workitem>) pm.newQuery(sql0).execute();
	    	pm.deletePersistentAll(results);
	    	System.out.println("deleted all!");*/
			//FIXME: limit
			String sql = "SELECT FROM " + Workitem.class.getName() + " where user_id == " + user_id + " order by created desc";
			List<Workitem> results= (List<Workitem>) pm.newQuery(sql).execute();
			int size = results.size()<10?results.size():10;
			for(int i=0; i<size; i++) {
				workitems.add(results.get(i));
			}
		} catch (Exception e) {
	    	LOG.logp(Level.FINE, "WorkitemServiceImpl", "loadWorkitems", e.toString());
	    } finally {
	    	pm.close();
	    }
		return workitems;
	}
	
	
}

